package com.zkk.dao.impl;

import com.zkk.dao.UserDao;
import com.zkk.pojo.User;
import com.zkk.utils.DruidUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate jdbcTemplate=new JdbcTemplate(DruidUtil.getDataSource());
    @Override
    public User login(User user) {
        List<User> query = jdbcTemplate.query("select * from user where username=? and password=?", new BeanPropertyRowMapper<>(User.class), user.getUsername(), user.getPassword());
        if (query!=null&&query.size()==1){
            return query.get(0);
        }
        return null;

    }

    @Override
    public List<User> findAll() {
        List<User> query = jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class));
        return query;
    }

    @Override
    public int deleteById(int id) {
        int update = jdbcTemplate.update("delete from user where id=?",id);
        return update;
    }

    @Override
    public int insertUser(int id, String username, String password) {
        int update = jdbcTemplate.update("insert  into user(id,username,password) values (?,?,?)",id,username, password);
        return update;
    }

    @Override
    public int modifyUser(int id,String username,String password) {
        int update = jdbcTemplate.update("update user set username=?,password=? where id=?", username, password,id );
        return update;
    }

    @Override
    public User findById(int id) {
        List<User> query = jdbcTemplate.query("select * from user where id=?", new BeanPropertyRowMapper<>(User.class), id);
        for (User user : query) {
            return user;
        }
        return null;
    }
}
